'''
Author: duliang thinktanker@163.com
Date: 2025-05-20 10:02:55
LastEditors: duliang thinktanker@163.com
LastEditTime: 2025-06-05 10:07:13
FilePath: 
Description: 
'''
import cv2
import serial
import time
import serial.tools.list_ports
from config import *
import json


def getCOMport(tag=''):
    '''
    找到单片机的端口，返回COM值
    '''
    # 获取所有串口设备实例。
    # 如果没找到串口设备，则输出：“无串口设备。”
    # 如果找到串口设备，则依次输出每个设备对应的串口号和描述信息。
    ports_list = list(serial.tools.list_ports.comports())
    if len(ports_list) <= 0:
        print("无串口设备。")
    else:
        print("有可用串口")
        # print(ports_list)
        for comport in ports_list:
            print(comport)
            if tag in list(comport)[1]:
                return list(comport)[0]
    return []


def send_data_to_serial(serial_port, baudrate=115200, chunk_size=1024):
    """
    通过串口发送文件
    参数：
    file_path: 要发送的文件路径
    serial_port: 串口号（字符串或列表）
    baudrate: 波特率（默认115200）py
    chunk_size: 每次发送的数据块大小（默认1024字节）
    """
    try:
        # 处理串口参数
        if isinstance(serial_port, list):
            serial_port = serial_port[0]
        # 初始化串口
        ser = serial.Serial(port=serial_port,
                            baudrate=baudrate,
                            bytesize=serial.EIGHTBITS,
                            parity=serial.PARITY_NONE,
                            stopbits=serial.STOPBITS_ONE,
                            timeout=1)
        print("连接成功，等待稳定")
        # time.sleep(20)
        # ser.write(b'200')
        i = 0
        while 1:
            i += 1
            print(i, end='\r')
            recv = ser.read(1024)
            if recv:
                print(recv)
                if b'200' in recv:
                    break
            if i > 10:
                break
            time.sleep(1)
    except Exception as e:
        print(f"串口连接失败: {e}")
        # return
    try:
        while True:
            # 初始化视频捕获
            with open("./config/rtsplist.json", "r", encoding="utf8") as f:
                rtsp_list = json.load(f)

            for key in rtsp_list.keys():
                size = (320, 240)
                rtsp_temp = rtsp_list[key]
                rtsp = rtsp_temp[0]
                if len(rtsp_temp) > 1:
                    size = tuple(rtsp_temp[1])
                cap = cv2.VideoCapture(rtsp, cv2.CAP_FFMPEG)
                if not cap.isOpened():
                    print(key, "无法连接RTSP流")
                    cap.release()
                    continue
                for _ in range(5):
                    ret, frame = cap.read()
                if not ret:
                    print("视频帧读取失败")
                    cap.release()
                    continue
                frame = cv2.resize(frame, size)
                # 将帧转换为JPEG字节流（可调整压缩质量）
                _, jpeg = cv2.imencode('.jpg', frame,
                                       [int(cv2.IMWRITE_JPEG_QUALITY), 70])

                jpeg_data = jpeg.tobytes()
                print(key, len(jpeg_data))
                with open('test.jpg', 'wb') as f:
                    f.write(jpeg_data)
                # 分块发送数据
                for offset in range(0, len(jpeg_data), chunk_size):
                    chunk = jpeg_data[offset:offset + chunk_size]
                    bytes_written = ser.write(chunk)
                    ser.flush()
                    # time.sleep(2)
                    print(f"已发送 {bytes_written} 字节")
                ser.write(f'((x:/{len(jpeg_data)}/{key}/zk.jpg))FIL'.encode())
                ser.flush()
                print("\n数据发送完成")
                cap.release()
                print("资源已释放")
                time.sleep(10)
            time.sleep(300)
    except Exception as e:
        print(f"\n发送失败: {e}")
    finally:
        ser.close()


# 使用示例
if __name__ == "__main__":
    print("开始运行")
    serial_port = getCOMport('USB-Enhanced-SERIAL CH343')  #正式用
    send_data_to_serial(serial_port)
